﻿
Option Compare Binary
Option Infer On
Option Strict On
Option Explicit On

Imports SilverlightSEO.Data
Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.ComponentModel.DataAnnotations
Imports System.Data.Linq
Imports System.Linq
Imports System.Web.DomainServices
Imports System.Web.DomainServices.Providers
Imports System.Web.Ria
Imports System.Web.Ria.Services

'<RequiresAuthentication> _
<EnableClientAccess()> _
Partial Public Class SiteDomainService
    Inherits LinqToSqlDomainService(Of SiteDataClassesDataContext)

    Private Sub CheckForDuplicate(ByVal page As Page)

        Dim duplicates = From p In Me.DataContext.Pages _
                            Where p.Title = page.Title _
                            AndAlso p.PageId <> page.PageId


        If duplicates.Count > 0 Then

            Throw New InvalidOperationException("Cannot add pages with duplicate titles")

        End If

    End Sub

    Private Sub SetLastModifiedProperties(ByRef page As Page)

        page.LastModified = Date.Now

        page.aspnet_User = (From a In Me.DataContext.aspnet_Users _
                           Where a.LoweredUserName = My.User.Name.ToLowerInvariant()).FirstOrDefault

        page.LastModifiedBy = page.aspnet_User.UserId

    End Sub

    Public Function GetPages() As IQueryable(Of Page)

        Return From p In Me.DataContext.Pages Order By p.SortIndex

    End Function

    Public Function GetPageByTitle(ByVal title As String) As IQueryable(Of Data.Page)

        Dim options As New DataLoadOptions()

        options.LoadWith(Of Data.Page)(Function(p As Data.Page) p.aspnet_User)

        Me.DataContext.LoadOptions = options

        title = System.Web.HttpUtility.UrlDecode(title)

        Dim results As IQueryable(Of Page) = _
            From p In Me.DataContext.Pages _
            Where p.Title = title

        If results.Count = 0 Then

            results = GetPages.Take(1)

        End If

        Return results

    End Function

    <RequiresRole("Administrators")> _
    Public Sub InsertPage(ByVal page As Page)
        Me.CheckForDuplicate(page)

        Me.SetLastModifiedProperties(page)

        'page.Title = page.Title.Replace("&", "%26")

        Me.DataContext.Pages.InsertOnSubmit(page)


    End Sub

    <RequiresRole("Administrators")> _
    Public Sub UpdatePage(ByVal currentPage As Page)

        Me.CheckForDuplicate(currentPage)

        Me.SetLastModifiedProperties(currentPage)

        'currentPage.Title = currentPage.Title.Replace("&", "%26")

        Me.DataContext.Pages.Attach(currentPage, Me.ChangeSet.GetOriginal(currentPage))

    End Sub

    <RequiresRole("Administrators")> _
    Public Sub DeletePage(ByVal page As Page)

        Me.DataContext.Pages.Attach(page)

        Me.DataContext.Pages.DeleteOnSubmit(page)

    End Sub

End Class

